package com.scale.service.user.service.impl;

import com.example.user.entity.UserPreferences;
import com.scale.service.user.mapper.UserPreferencesMapper;
import com.scale.service.user.service.UserPreferencesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户偏好设置表 服务实现类
 * </p>
 *
 * @author crp
 * @since 2025-09-23
 */
@Service
public class UserPreferencesServiceImpl extends ServiceImpl<UserPreferencesMapper, UserPreferences> implements UserPreferencesService {

    @Override
    public UserPreferences getUserPreferences(Long userId) {
        QueryWrapper<UserPreferences> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        
        UserPreferences preferences = getOne(queryWrapper);
        
        // 如果用户没有偏好设置，创建默认设置
        if (preferences == null) {
            preferences = createDefaultPreferences(userId);
        }
        
        return preferences;
    }

    @Override
    public UserPreferences updateUserPreferences(UserPreferences preferences) {
        QueryWrapper<UserPreferences> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", preferences.getUserId());
        
        UserPreferences existing = getOne(queryWrapper);
        
        if (existing != null) {
            // 更新现有设置
            preferences.setId(existing.getId());
            preferences.setCreatedAt(existing.getCreatedAt());
            preferences.setUpdatedAt(LocalDateTime.now());
            updateById(preferences);
        } else {
            // 创建新设置
            preferences.setCreatedAt(LocalDateTime.now());
            preferences.setUpdatedAt(LocalDateTime.now());
            save(preferences);
        }
        
        return preferences;
    }
    
    /**
     * 创建默认用户偏好设置
     */
    private UserPreferences createDefaultPreferences(Long userId) {
        UserPreferences preferences = new UserPreferences();
        preferences.setUserId(userId);
        preferences.setPreferredCharacterType("friend");
        preferences.setVoiceSpeed(BigDecimal.valueOf(1.0));
        preferences.setVoicePitch(BigDecimal.valueOf(1.0));
        preferences.setAutoEmotionDetection(true);
        preferences.setPrivacyLevel(1);
        preferences.setNotificationEnabled(true);
        preferences.setCreatedAt(LocalDateTime.now());
        preferences.setUpdatedAt(LocalDateTime.now());
        
        save(preferences);
        return preferences;
    }
}
